package com.example.obtaingaode.activity;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.example.obtaingaode.LineServer;
import com.example.obtaingaode.R;
import com.example.obtaingaode.bean.CommonBean;
import com.example.obtaingaode.bean.SetBean;
import com.example.obtaingaode.bean.UserInfomation;
import com.example.obtaingaode.bean.Userbean;
import com.example.obtaingaode.db.DbEntity;
import com.example.obtaingaode.db.DbEntity_;
import com.example.obtaingaode.db.LineEntrty;
import com.example.obtaingaode.db.LineEntrty_;
import com.example.obtaingaode.di.DaggerActivityComponent;
import com.example.obtaingaode.net.MApi;
import com.example.obtaingaode.thread.SaveExcelThread;
import com.example.obtaingaode.util.ConfigInfomation;
import com.example.obtaingaode.util.Constants;
import com.example.obtaingaode.util.HintUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.QMUIProgressBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.trello.rxlifecycle2.android.ActivityEvent;


import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.MonthDisplayHelper;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;


import javax.inject.Inject;

import frame.m.com.mylibrary.common.HintView;
import frame.m.com.mylibrary.http.BaseResult;
import frame.m.com.mylibrary.http.HttpConstant;
import frame.m.com.mylibrary.http.HttpUtil;
import frame.m.com.mylibrary.http.ProgressSubscriber;
import frame.m.com.mylibrary.http.RetrofitUtil;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import io.objectbox.query.QueryBuilder;
import io.reactivex.Observable;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public class HomeActivity extends CheckPermissionsActivity implements AMapLocationListener,
        View.OnClickListener, ServiceConnection {
    public final PublishSubject<ActivityEvent> lifecycleCallbacksPublishSubject = PublishSubject
            .create();
    /**
     * 定位管理
     */
    private AMapLocationClient mLocationClient = null;
    /**
     * 声明mLocationOption对象
     */
    public AMapLocationClientOption mLocationOption = null;

    public final String FILE_NAME = "qiangxiu";

    private TextView tvTitle;
    private RelativeLayout llRight;
    private TextView tvPoint;
    private TextView tvGetPoint;
    private TextView tvSumbit;
    private EditText etNumber;
    private TextView tvStartLineServer;
    private TextView tvUploadLine;
    private TextView tvShowPoint;
    private RelativeLayout rlSet;
    private int mPostion;
    private OptionsPickerView pv;
    private TextView tvSaveExl;

    private List<SetBean> mSetBeans;

    private QMUIDialog mDialog;
    public String location;
    private LineServer.Binder binder;
    public static final String LINE_SERVER_START = "lineServerStart"; //服务正在运行
    public static final String LINE_SERVER_END = "lineServerEnd"; //服务已停止


    @Inject
    public MApi mApi;
    @Inject
    public HttpUtil mHttpUtil;
    @Inject
    BoxStore boxStore;
    @Inject
    Box<DbEntity> dbEntityBox;
    @Inject
    Box<LineEntrty> lineEntrtyBox;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        ActionBar actionBar = getActionBar(); // 得到ActionBar
//        actionBar.hide(); // 隐藏ActionBar
        initView();
        DaggerActivityComponent.builder().appComponent(MyApplication.getAppComponent()).build()
                .inject(this);
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llRight = (RelativeLayout) findViewById(R.id.rl_right);
        tvPoint = (TextView) findViewById(R.id.tv_point);
        tvGetPoint = (TextView) findViewById(R.id.tv_get_point);
        tvSumbit = (TextView) findViewById(R.id.tv_sumbit);
        etNumber = (EditText) findViewById(R.id.et_number);
        tvShowPoint = (TextView) findViewById(R.id.textView2);
        rlSet = (RelativeLayout) findViewById(R.id.rl_set);
        tvSaveExl= (TextView) findViewById(R.id.tv_import_exl);

        tvStartLineServer = (TextView) findViewById(R.id.tv_start_line_server);
        tvUploadLine = (TextView) findViewById(R.id.tv_upload_line);
        tvStartLineServer.setTag(LINE_SERVER_END);
        llRight.setOnClickListener(this);
        tvGetPoint.setOnClickListener(this);
        tvSumbit.setOnClickListener(this);
        tvShowPoint.setOnClickListener(this);
        rlSet.setOnClickListener(this);
        tvSaveExl.setOnClickListener(this);
        initLocation();
        readConfig();
        String userNo = UserInfomation.getUserNo();
        String username = UserInfomation.getUserName();
        tvUploadLine.setOnClickListener(this);
        if (!TextUtils.isEmpty(userNo)) {
            tvTitle.setText(String.format("录入系统(%s)", username));
            tvTitle.setTag(userNo);
        }
    }

    private void initLocation() {
        // 初始化定位
        mLocationClient = new AMapLocationClient(this);
        // 设置定位回调监听
        mLocationClient.setLocationListener(this);
        // 初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅111模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        // 设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        // 设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        // 设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        // 设置定位间隔,单位毫秒,默认为10*2000ms
        mLocationOption.setInterval(10 * 3000);
        // 给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 启动定位
        mLocationClient.startLocation();
    }

    public void startLocation() {
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null && amapLocation.getErrorCode() == 0) {
            double latitu = amapLocation.getLatitude();// 获取纬度
            double longitu = amapLocation.getLongitude();// 获取经度
            DecimalFormat decimalFormat = new DecimalFormat("0.00000000");
            location = String.format("%s,%s",
                    "" + decimalFormat.format(longitu) + "",
                    "" + decimalFormat.format(latitu));
            tvPoint.setText(location);
        } else {
            // 显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
            Log.e("AmapError",
                    "location Error, ErrCode:" + amapLocation.getErrorCode()
                            + ", errInfo:" + amapLocation.getErrorInfo());
        }
    }

    private void readConfig() {
        mSetBeans = new Gson().fromJson(readFile(),
                new TypeToken<List<SetBean>>() {
                }.getType());
    }

    public String readFile() {
        String str = null;
        try {
            InputStream is = getAssets().open(FILE_NAME);
            int lenght = is.available();
            byte[] buffer = new byte[lenght];
            is.read(buffer);
            str = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    private void pop() {
        List<String> option1 = getOptionsByBean(mSetBeans);
        pv = new OptionsPickerView<String>(new OptionsPickerView.Builder(this,
                new OptionsPickerView.OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int options2,
                                                int options3, View v) {
                        tvGetPoint.setText(mSetBeans.get(options1).getValue());
                        tvGetPoint.setTag("" + options1);
                    }
                }) {

        }.isDialog(true));
        pv.setPicker(option1);
        pv.show();
    }

    private List<String> getOptionsByBean(List<SetBean> mSetBeans2) {
        List<String> option1 = new ArrayList<>();
        for (SetBean setBean : mSetBeans2) {
            option1.add(setBean.getValue());
        }
        return option1;
    }


    @Override
    public void setContentView(View view) {
        super.setContentView(view);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_right:
                // 绑定人员的界面
                popCountChoose();
                break;
            case R.id.tv_get_point:
                pop();
                break;
            case R.id.tv_sumbit:
                clickSave();
                break;
            case R.id.tv_upload_line:
                popUploadLinePoint();
                break;
            case R.id.textView2:
                Intent intent = new Intent(HomeActivity.this, ShowDbActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_set:
                popSet();
                break;
            case R.id.tv_import_exl:
                startThread();
                break;
            default:
                break;
        }

    }

    private void popSet() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        mDialog = builder.setTitle("请输入新的域名")
                .setPlaceholder(ConfigInfomation.getBaseUrl(Constants.HOST)).addAction("取消", new
                        QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                mDialog.dismiss();
                            }
                        }).addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String s = builder.getEditText().getText().toString();
                        if (TextUtils.isEmpty(s)) {
                            mDialog.dismiss();
                        } else {
                            ConfigInfomation.saveBaseUrl(s);
                            mDialog.dismiss();
                        }
                    }
                }).create();
        builder.getEditText().setText(ConfigInfomation.getBaseUrl(Constants.HOST));
        mDialog.show();
    }

    private void clickSave() {
        String location = tvPoint.getText().toString();
        String userNo = (String) tvTitle.getTag();
        String postion = (String) tvGetPoint.getTag();
        String deviceNo = etNumber.getText().toString();
        if (TextUtils.isEmpty(location)) {
            HintUtil.showErrorStr(this, "定位失败!");
            return;
        }
        if (TextUtils.isEmpty(userNo)) {
            HintUtil.showErrorStr(this, "获取用户信息失败,请点击设置按钮设置人员");
            return;
        }
        if (TextUtils.isEmpty(postion)) {
            HintUtil.showErrorStr(this, "请先选择采集点信息");
            return;
        }
        if (TextUtils.isEmpty(deviceNo)) {
            HintUtil.showErrorStr(this, "请先输入设备编号");
            return;
        }
        deviceNo = deviceNo.trim();

        int nPostion = Integer.valueOf(postion);
        String deviceType = mSetBeans.get(nPostion).getKey();
        String remark = mSetBeans.get(nPostion).getValue();
        Map<String, String> map = new HashMap<String, String>();
        map.put("actionName", Constants.URL_SAVE);
        map.put("positionData", location);
        map.put("deviceType", deviceType);
        map.put("deviceNo", deviceNo);
        map.put("remark", remark);
        map.put("userNo", userNo);
        requestSave(map, SaveDb(map));
//      Logger.d(new Gson().toJson(dbEntityBox.getAll()));


    }

    private long SaveDb(Map<String, String> map) {
        DbEntity dbEntity = new DbEntity(0, map.get("positionData"), map.get("deviceType"), map
                .get("deviceNo"), map.get("remark"), map.get("userNo"), false);
        long put = dbEntityBox.put(dbEntity);
        Logger.d("数据库的数据是>>>>>" + dbEntityBox.count() + "\nid是>>>>>" + put);
        return put;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle
            persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    private void requestSave(Map<String, String> map, final long putId) {
//        showLoadingAndStay();
        String url = String.format("%s?para=%s", Constants.getBaseUrl(), new Gson()
                .toJson(map).toString());
        Observable<BaseResult<String>> ob = mApi
                .save(url);
        mHttpUtil.toSubcribe(ob, new ProgressSubscriber<String>(HomeActivity
                .this) {
            @Override
            protected void _onNext(String o) {
                HintUtil.showSuccessStr(HomeActivity.this, "保存成功");
                updateAleady(putId);
            }
        }, ActivityEvent.PAUSE, lifecycleCallbacksPublishSubject);

    }

    private void updateAleady(long putId) {
        List<DbEntity> dbEntities = dbEntityBox.query().equal(DbEntity_.id, putId).build().find();
        if (dbEntities.isEmpty()) {
            return;
        }
        DbEntity dbEntity = dbEntities.get(0);
        dbEntity.setSaveNet(true);
        dbEntityBox.put(dbEntity);
    }

    /**
     * 弹出绑定用户的
     */
    private void popCountChoose() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog
                .EditTextDialogBuilder(this);
        mDialog = builder.setPlaceholder("请输入人员编号")
                .addAction("取消", new QMUIDialogAction
                        .ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        mDialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String text = builder.getEditText().getText().toString();
                        reqeustGetUser(text);
                        mDialog.dismiss();
                    }
                }).setTitle("请输入人员编号").create();
        mDialog.show();
    }

    /**
     * 获取用户
     */
    private void reqeustGetUser(String str) {
        if (TextUtils.isEmpty(str)) {
            HintUtil.showErrorStr("请输入用户编号");
            return;
        }
        Logger.d(new Userbean("aaa", "1111", "1111", "aaaaa"));
        Map<String, String> map = new HashMap<String, String>();
        map.put("userNo", str);
        map.put("actionName", Constants.URL_LOGIN);
        String url = String.format("%s?para=%s", Constants.getBaseUrl(), new Gson()
                .toJson(map).toString());

        Observable<BaseResult<Userbean>> ob = mApi
                .login(url);
        mHttpUtil.toSubcribe(ob, new ProgressSubscriber<Userbean>(this) {
            @Override
            protected void _onNext(Userbean o) {
                UserInfomation.saveUser(o);
                tvTitle.setText(String.format("%s(%s)", "录入系统", o.getUserName()));
                tvTitle.setTag(o.getUserNo());
                HintView.getInstance().showSuccess(HomeActivity.this, "用户信息设置成功!");
            }
        }, ActivityEvent.PAUSE, lifecycleCallbacksPublishSubject);
    }

    public void goNext(View v) {
        Intent intent = new Intent(HomeActivity.this, ShowDbActivity.class);
        startActivity(intent);
    }

    public void startLineServer(View v) {
        if (((String) v.getTag()).equals(LINE_SERVER_START)) {
            endServer();
            v.setTag(LINE_SERVER_END);
            ((TextView) v).setText("开始记录轨迹");
        } else if (((String) v.getTag()).equals(LINE_SERVER_END)) {
            startServer();
            v.setTag(LINE_SERVER_START);
            ((TextView) v).setText("轨迹记录中...");
        }
    }

    private void endServer() {
        unbindService(this);
    }


    /**
     * 开启记录位置点的服务
     */
    private void startServer() {
        Intent intent = new Intent(this, LineServer.class);
        bindService(intent, this, BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        binder = (LineServer.Binder) iBinder;
        binder.getLineServere().setCallback(new LineServer.SendCallback() {
            @Override
            public void getLocation() {
                binder.setLocation(location);
            }

            @Override
            public void saveLineSuccess() {
                updateSaveLineCount();
            }

            @Override
            public void changeLocation() {
                /**
                 * 在息屏状态下,每隔2s会触发重新定位的方法
                 */
                startLocation();
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Logger.d("服务已停止...");
    }

    private void updateSaveLineCount() {
        if (((String) tvStartLineServer.getTag()).equals(LINE_SERVER_START)) {

        }
    }

    /**
     * 上传未上传的轨迹信息
     */
    private void popUploadLinePoint() {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(this);
        final List<LineEntrty> lineEntrties = lineEntrtyBox.query().equal(LineEntrty_.isUpload,
                false)
                .build().find();
        if (lineEntrties.size() == 0) {
            mDialog = dialogBuilder.setTitle("提示").setMessage("当前所有轨迹信息已上传,无需重复上传").addAction
                    ("是", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            mDialog.dismiss();
                        }
                    }).create();
            mDialog.show();
            return;
        }
        mDialog = dialogBuilder.setTitle("提示").setMessage(String.format("当前有%s条信息未上传,是否上传",
                lineEntrties.size())).addAction("否", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                mDialog.dismiss();

            }
        }).addAction("是", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                mDialog.dismiss();
                uploadAllUnLinePoint(lineEntrties);
            }
        }).create();
        mDialog.show();
    }

    private void uploadAllUnLinePoint(List<LineEntrty> lineEntrties) {
        int size = lineEntrties.size();
        showProgressDialog();
        setMaxProgress(size);
        for (LineEntrty lineEntrty : lineEntrties) {
            Map<String, String> map = new HashMap<>();
            final long id = lineEntrty.getId();
            map.put("actionName", Constants.URL_SAVE);
            map.put("positionData", lineEntrty.getLocation());
            map.put("deviceType", lineEntrty.getType());
            map.put("deviceNo", "-1");
            map.put("remark", "-1");
            map.put("userNo", lineEntrty.getNumber());
            String url = String.format("%s?para=%s", Constants.getBaseUrl(), new Gson()
                    .toJson(map).toString());
            Observable<BaseResult<String>> ob = mApi
                    .save(url);
            ob.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe
                    (new DisposableObserver<BaseResult<String>>() {
                        @Override
                        public void onNext(@NonNull BaseResult<String> commonBeanBaseResult) {
                            if (commonBeanBaseResult.isSuccess()) {
                                Logger.d("%s的数据上传成功!", id);
                                setUploadTrueById(id);
                                addNowProgress();
                            } else {
                                addErrorProgress();
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            addErrorProgress();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }


    /**
     * 根据id更改数据库里面的isUoload标签为true
     *
     * @param id
     */
    private void setUploadTrueById(Long id) {
        List<LineEntrty> lineEntrties = lineEntrtyBox.find(LineEntrty_.id, id);
        if (lineEntrties.isEmpty()) {
            return;
        }
        LineEntrty lineEntrty = lineEntrties.get(0);
        lineEntrty.setIsUpload(true);
        long changeId = lineEntrtyBox.put(lineEntrty);
        Logger.d("id为%s的数据更改上传状态为true", "" + changeId);
    }

    /**
     * 显示进度条
     */
    private void showProgressDialog() {
        mDialog = new QMUIDialog.CustomDialogBuilder(this).setLayout(R.layout
                .progress_bar).create();
        QMUIProgressBar view = (QMUIProgressBar) mDialog.findViewById(R.id.rectProgressBar);
        view.setTag(R.id.success, 0);
        view.setTag(R.id.error, 0);
        view.setQMUIProgressBarTextGenerator(new QMUIProgressBar.QMUIProgressBarTextGenerator() {
            @Override
            public String generateText(QMUIProgressBar progressBar, int value, int maxValue) {
                return String.format("%d/%d", value, maxValue);
            }
        });
        mDialog.show();
    }

    /**
     * 设置失败的数量
     */
    private void addErrorProgress() {
        if (getProgressView() == null) {
            return;
        }
        QMUIProgressBar progressView = getProgressView();
        Object errorCount = progressView.getTag(R.id.error);
        if (errorCount == null) {
            errorCount = 0;
        }
        progressView.setTag(R.id.error, ((int) errorCount) + 1);
        chooseIsEndUoload();
    }

    /**
     * 判断是否已经上传完毕
     */
    private void chooseIsEndUoload() {
        QMUIProgressBar progressView = getProgressView();
        if (progressView.getTag(R.id.success) == null || progressView.getTag(R.id.error) == null) {
            return;
        }
        if (((Integer) progressView.getTag(R.id.error)) + ((Integer) progressView.getTag(R.id
                .success)) >= progressView
                .getMaxValue()) {
            mDialog.dismiss();
            if (((Integer) progressView.getTag(R.id.error)) == 0) {
                mDialog = new QMUIDialog.MessageDialogBuilder(this).setMessage("上传完毕").addAction
                        ("确定", new QMUIDialogAction.ActionListener() {

                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                mDialog.dismiss();
                            }
                        }).create();
            } else {
                mDialog = new QMUIDialog.MessageDialogBuilder(this).setMessage(String.format
                        ("上传完毕,但是仍有%d条数据未上传,是否继续上传", ((Integer) progressView.getTag(R.id.error))))
                        .addAction("否", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                mDialog.dismiss();
                            }
                        }).addAction("是", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                mDialog.dismiss();
                                final List<LineEntrty> lineEntrties = lineEntrtyBox.query().equal
                                        (LineEntrty_.isUpload,
                                                false)
                                        .build().find();
                                uploadAllUnLinePoint(lineEntrties);
                            }
                        }).create();
            }
            mDialog.show();
        }
    }

    private void addNowProgress() {
        if (getProgressView() == null) {
            return;
        }
        QMUIProgressBar progressView = getProgressView();
        progressView.setProgress(progressView.getProgress() + 1);
        Object successCount = progressView.getTag(R.id.success);
        if (successCount == null) {
            successCount = 0;
        }
        progressView.setTag(R.id.success, ((Integer) successCount) + 1);
        chooseIsEndUoload();
    }

    private void setMaxProgress(int maxProgress) {
        if (getProgressView() == null) {
            return;
        }
        getProgressView().setMaxValue(maxProgress);
    }

    private QMUIProgressBar getProgressView() {
        View view = mDialog.findViewById(R.id.rectProgressBar);
        if (view instanceof QMUIProgressBar) {
            return ((QMUIProgressBar) view);
        }
        return null;
    }

    /**
     * 生成excel表格
     */
    private void startThread() {
        new SaveExcelThread(handler).run();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                ToastUtils.showShort("导出失败");
            }
            else {
                mDialog=new QMUIDialog.MessageDialogBuilder(HomeActivity.this).setMessage((
                        (String) msg.obj)).addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        mDialog.dismiss();
                    }
                }).create();
                mDialog.show();
            }
        }
    };


}
